<template>
	<view class="weather-container">

		<!-- 展示定位详细 -->
		<view v-if="weather.adcode" class="weather">
			<view class="icon">
				<image :src="this.getIcon(weather.casts[0].dayweather)"></image>
			</view>

			<view class="info">
				<view class="top">
					{{ weather.city }}
					<view class="temp">
						{{ weather.now }}°
					</view>

				</view>
				<view class="bottom">
					<view class="box" v-for="(item, i) in weather.casts" :key="i">
						<view class="day">
							&nbsp; &nbsp; &nbsp; 星期{{ week[item.week - 1] }}
						</view>
						<view class="temp">
							<image :src="getIcon(item.dayweather)"></image> {{ item.daytemp }}°
						</view>
					</view>
				</view>
			</view>
		</view>


		<!-- 未获取到定位权限 -->
		<view v-if="!IsPermission">
			<button @click='toSetting' type="primary" size="default">
				重新定位</button>
		</view>

	</view>
</template>

<script>
import {
	mapMutations
} from 'vuex'
import config from "@/config/index.js"
export default {
	name: "Weather",
	data() {
		return {
			city: {
				name: '北京',
				district: '',
				adcode: 110105, //城市代码
			},
			IsPermission: true, //获取定位权限
			weather: {},
			week: ['一', "二", "三", "四", "五", "六", "日"]
		};
	},
	methods: {
		...mapMutations('weather', ['updateWeather', 'updateLocation']),
		//获取具体经纬度
		getLocation() {
			uni.getLocation({
				type: 'wgs84',
				success: async (res) => {
					const local = res.longitude + ',' + res.latitude
					this.updateLocation({
						longitude: res.longitude,
						latitude: res.latitude
					})
					this.getCity(local, this.getWeatherByCity)
				},
				fail: (res) => {
					console.log(res);
					if (res.errMsg === "getLocation:fail auth deny") {
						wx.showToast({
							title: '获取定位失败',
							icon: 'error'
						})
						this.IsPermission = false
					}
				},
			});
		},

		//取消授权后重新获取定位
		toSetting() {
			wx.openSetting({
				success: (res) => {
					if (res.authSetting["scope.userLocation"]) {
						// res.authSetting["scope.userLocation"]为trueb表示用户已同意获得定位信息，此时调用getlocation可以拿到信息
						wx.getLocation({
							type: 'wgs84',
							success: (res) => {
								console.log(res)
								const local = res.longitude + ',' + res.latitude
								this.IsPermission = true
								this.getCity(local)
							}
						})
					}
				}
			})
		},

		// 根据经纬度获取城市
		async getCity(local, db) {
			const url = 'https://restapi.amap.com/v3/geocode/regeo'
			const data = {
				key: config.key,
				location: local
			}
			try {
				uni.request({
					url,
					method: 'GET',
					data,
					success: (ret) => {
						if (ret.data.info === 'OK') {
							const address = ret.data.regeocode.addressComponent

							this.city.name = address.city
							this.city.district = address.district
							this.city.adcode = address.adcode
							db && db(address.adcode)
						}
					}
				})
			} catch (error) {
				console.log('获取位置失败', error);
			}
		},

		// 获取天气接口
		getWeatherByCity(adcode) {
			const data = {
				city: adcode,
				key: config.key,
				extensions: 'all'
			}
			// 获取预测天气
			wx.request({
				url: 'https://restapi.amap.com/v3/weather/weatherInfo',
				method: 'get',
				data,
				success: (ret) => {
					if (ret.statusCode == 200) {
						const weather = ret.data.forecasts[0]

						weather.now = ''
						this.weather = weather

						//获取实时天气
						data.extensions = 'base'
						wx.request({
							url: 'https://restapi.amap.com/v3/weather/weatherInfo',
							method: 'get',
							data,
							success: (ret) => {
								if (ret.statusCode == 200) {
									const weather = ret.data.lives[0]
									this.weather.now = weather.temperature
									console.log('天气信息', this.weather)
									const {
										city,
										now,
									} = this.weather
									// 本地存储天气信息
									this.updateWeather({
										city,
										now,
										icon: this.getIcon(this.weather.casts[0].dayweather)
									})
								}
							}
						})
					}
				}
			})
		},


		/**
		 * 根据天气现象返回其图标icon url
		 * @param {String} weather 天气现象
		 * @returns 天气现象对应的某一类的url
		 */
		getIcon(weather) {
			/**
			 * 图标和天气现象的映射关系
			 * key: 某一类天气现象，这个key会和icon名一一对应
			 * value: 某一类下天气现象，可以按照自己的需求划分分类
			 */
			const iconWeatherMap = {
				'wind': ['有风', '平静', '微风', '和风', '清风', '强风/劲风', '疾风', '大风', '烈风', '风暴', '狂爆风', '飓风', '热带风暴',
					'龙卷风'
				],
				'cloudy': ['少云', '晴间多云', '多云'],
				'snow': ['雪', '阵雪', '小雪', '中雪', '大雪', '暴雪', '小雪-中雪', '中雪-大雪', '大雪-暴雪', '冷'],
				'fog': ['浮尘', '扬沙', '沙尘暴', '强沙尘暴', '雾', '浓雾', '强浓雾', '轻雾', '大雾', '特强浓雾'],
				'sun': ['晴', '热'],
				'sleet': ['雨雪天气', '雨夹雪', '阵雨夹雪'],
				'rain': ['阵雨', '雷阵雨', '雷阵雨并伴有冰雹', '小雨', '中雨', '大雨', '暴雨', '大暴雨', '特大暴雨', '强阵雨', '强雷阵雨', '极端降雨',
					'毛毛雨/细雨', '雨', '小雨-中雨', '中雨-大雨', '大雨-暴雨', '暴雨-大暴雨', '大暴雨-特大暴雨', '冻雨'
				],
				'overcast': ['阴', '霾', '中度霾', '重度霾', '严重霾', '未知']
			}
			// 这个是icon的默认值
			let url = 'https://elderlycomm.oss-cn-chengdu.aliyuncs.com/images/sun.png'

			for (const weatherKey in iconWeatherMap) {
				if (Object.hasOwnProperty.call(iconWeatherMap, weatherKey)) {
					const weatherNames = iconWeatherMap[weatherKey]
					const findWeatherItem = weatherNames.find(name => weather === name)

					// 如果找了某一类的图标了，那重新复制url
					if (findWeatherItem) {
						url = `https://elderlycomm.oss-cn-chengdu.aliyuncs.com/images/${weatherKey}.png`
						break
					}
				}
			}

			return url
		},

	},
	mounted() {
		this.getLocation()
	},
	onShow() {
		this.getLocation()
	}
}
</script>

<style lang="less" scoped>
.weather-container {
	height: 120px;
	width: 96%;
	background-color: #07689F;
	margin-left: 2%;
	box-shadow: 3px 3px 3px 1px rgba(0, 0, 0, 0.2);
	border-radius: 10px;
	margin-bottom: 20px;
	box-sizing: border-box;
}

.weather {
	height: 120px;
	width: 96%;
	display: flex;
	align-items: center;
	padding: 0 10px;
	font-size: 22px;
	color: white;
	font-family: 楷体;
	line-height: 28px;

	.info {
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.top {
			width: 100%;
			height: 50px;
			line-height: 50px;
			display: flex;
			flex-direction: row;
			padding-left: 49%;

			.temp {
				margin-left: 25rpx;
				font-size: 80rpx;
				font-weight: 800;

			}
		}
	}

	.bottom {
		display: flex;
		margin-bottom: -10px;

		.box {
			text-align: center;
			width: 140rpx;

			.day {
				font-size: 35rpx;
				margin-bottom: -10px;
			}

			.temp {
				font-size: 35rpx;
				align-items: center;

				image {
					width: 40rpx;
					height: 40rpx;
					padding: 20rpx 15rpx 0 15rpx;
				}
			}
		}
	}

	.icon {
		flex: 1;

		image {
			width: 100rpx;
			height: 100rpx;
		}
	}
}
</style>
